package ar.edu.itba.twiteros.util;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import com.google.code.facebookapi.FacebookException;
import com.google.code.facebookapi.FacebookJsonRestClient;

public class Facebook {
	
	private static final String fb_appkey = "9df3acaf513ff0d0b32ffcd54ffe9725";
	
	private static final String fb_appsecret = "b01f69e700017807f81847b468e0ba58";
	
	private static final String addUrl= "http://www.facebook.com/login.php?api_key=" + fb_appkey;
	
	private FacebookJsonRestClient client;
	
	public Facebook(String session){
		client= new FacebookJsonRestClient(fb_appkey, fb_appsecret, session);
	}
	
	public FacebookJsonRestClient getClient(){
		return client;
	}
	
	public long getUserId(){
		try{
			return this.client.users_getLoggedInUser();
		}catch (Exception e){
			return 0;
		}
		
	}
	
	/**
	 * Returns a string with the uids of the friends
	 * who didn't install the app
	 * @return
	 * @throws JSONException
	 * @throws ParseException
	 */
	public String getUidsFriends() throws JSONException, ParseException{
		Object obj=null;
		JSONArray jsonText=null;
		String result="";
		
		try {
			String fql = "SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1="+ client.users_getLoggedInUser() + ") AND has_added_app = 1";
			obj=client.fql_query(fql);
		} catch (FacebookException e) {
			e.printStackTrace();
		} 
		
		
		if(obj!=null){
			jsonText=(JSONArray)obj;
			JSONParser parser= new JSONParser();
			KeyFinder finder= new KeyFinder();
			
			finder.setMatchKey("uid");
			  
		    while(!finder.isEnd()){
		    	parser.parse(jsonText.toString(), finder, true);
		    	if(finder.isFound()){
		    		finder.setFound(false);
		    		result += (finder.getValue()) + ", ";
		    	}
		    }           	 
		    result= result.substring(0, result.length()-1);    
		}
		
		return result;
	}
	
	
	public String getAddUrl(){
		return addUrl;
	}

	public static String getFb_appkey() {
		return fb_appkey;
	}

	public static String getFb_appsecret() {
		return fb_appsecret;
	}
	

	
	
}
